package com.braveman.im.ui.activity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.braveman.im.R;
import com.braveman.im.bean.PersonalDataBaen;
import com.braveman.im.constant.Constants;
import com.braveman.im.factory.FragmentFactory;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.service.PushService;
import com.braveman.im.ui.activity.message.LoginActivity;
import com.braveman.im.ui.adapter.FragAdapter;
import com.braveman.im.ui.weiget.MenuPopup;
import com.braveman.im.utils.AppUtils;
import com.braveman.im.utils.UtilsStyle;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.DeviceUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.igexin.sdk.PushManager;
import com.vondear.rxtools.RxBarTool;

import java.util.ArrayList;
import java.util.List;

import cn.magicwindow.mlink.annotation.MLinkDefaultRouter;
import retrofit2.Call;
import retrofit2.Response;

@MLinkDefaultRouter
public class HomeActivity extends BaseActivity {
    private long exitTime;
    private ViewPager mPagerView;
    private TextView mTvHomeTabMessage;
    private TextView mTvHomeTabCircleFriends;
    private TextView mTvHomeTabResource;
    private TextView mTvHomeTabShoppingFriends;
    private TextView mTvHomeTabSelf;
    private FragAdapter adapter;
    private MenuPopup mMenuPopup;


    public HomeActivity() {
    }

    @Override
    protected boolean hasEvent() {
        return true;
    }

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
    }


    @Override
    protected void initTitleBar() {

        mTitleBarView.setTitleText("正气诚信").setLeftBtnIcon(R.mipmap.title_icon_search).addActions(new TitleBarView.Action(R.mipmap.title_icon_more) {
            @Override
            public void performAction(View view) {
                mMenuPopup = new MenuPopup(HomeActivity.this);
                mMenuPopup.showPopupWindow(view);
            }

        });
        mTitleBarView.setOnLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //  UIUtils.showToast("搜索功能");
                //         ActivityUtils.startActivity(HomeActivity.this, SearcharrsActivity.class);
                ActivityUtils.startActivity(HomeActivity.this, HomeSearchActivity.class);
            }
        });
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_home;
    }

    @Override
    protected void initChildView() {
        mPagerView = findViewById(R.id.pager_view);
        mTvHomeTabMessage = findViewById(R.id.tv_home_tab_message);
        mTvHomeTabCircleFriends = findViewById(R.id.tv_home_tab_circle_friends);
        mTvHomeTabResource = findViewById(R.id.tv_home_tab_resource);
        mTvHomeTabShoppingFriends = findViewById(R.id.tv_home_tab_shopping_friends);
        mTvHomeTabSelf = findViewById(R.id.tv_home_tab_self);
        resetTab();
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB0));
        fragments.add(FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB1));
        fragments.add(FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB2));
        fragments.add(FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB3));
        fragments.add(FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB4));
        adapter = new FragAdapter(getSupportFragmentManager(), fragments);
        mPagerView.setAdapter(adapter);

    }

    @Override
    protected void initChildData() {
        mTvHomeTabResource.setSelected(true);
        mPagerView.setCurrentItem(FragmentFactory.FRAGMENT_HOME_TAB2);
        // TODO: 2017/11/2 请求个人中心的接口存在本地并提取
        ApiManager.getApi().getPersonalData().enqueue(new NetCallBack<PersonalDataBaen>() {
            @Override
            protected void onSuccess(Call<PersonalDataBaen> call, Response<PersonalDataBaen> response) {
                PersonalDataBaen body = response.body();
                SharedPreferencesUtils.put(Constants.MINNAME, body.name);
                SharedPreferencesUtils.put(Constants.MINNUMBER, body.sn);
                SharedPreferencesUtils.put(Constants.MINIMG, body.avatar);
                // TODO: 17/11/2 获取诚信群too10对应关系
            }
        });
    }

    @Override
    protected void setChildViewListener() {
        mTvHomeTabMessage.setOnClickListener(this);
        mTvHomeTabCircleFriends.setOnClickListener(this);
        mTvHomeTabResource.setOnClickListener(this);
        mTvHomeTabShoppingFriends.setOnClickListener(this);
        mTvHomeTabSelf.setOnClickListener(this);
        mPagerView.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                doChangeFrag(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        doChangeFrag(v.getId());
    }


    private void resetTab() {
        mTvHomeTabMessage.setSelected(false);
        mTvHomeTabCircleFriends.setSelected(false);
        mTvHomeTabResource.setSelected(false);
        mTvHomeTabShoppingFriends.setSelected(false);
        mTvHomeTabSelf.setSelected(false);
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            checkFinishApp(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private void checkFinishApp(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                UIUtils.showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                ActivityUtils.finishActivityByAlpha(this);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        FragmentFactory.mHomeTabMap.clear();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);


        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:// 音量增大
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume + 1, 1);
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:// 音量减小
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume - 1, 1);
                break;


            case KeyEvent.KEYCODE_BACK:// 返回键
                //jniOnCallCppEvent();
                return true;
            //return super.onKeyDown(keyCode, event);


            default:
                break;
        }

        return true;
        //return super.onKeyDown(keyCode, event);
    }

    private void doChangeFrag(int position) {
        resetTab();
        switch (position) {
            case R.id.tv_home_tab_message:
                if (doIsLogin()) return;
                mPagerView.setCurrentItem(FragmentFactory.FRAGMENT_HOME_TAB0);
                break;
            case 0:
                if (doIsLogin()) return;
                doChangeTitleLeftIcon(1);
                mTvHomeTabMessage.setSelected(true);
                mTitleBarView.setTitleText("消息");
                String s = DeviceUtils.getDeviceId() + "";
                Log.e("---------", s);
                break;
            case R.id.tv_home_tab_circle_friends:
                if (doIsLogin()) return;
                mPagerView.setCurrentItem(FragmentFactory.FRAGMENT_HOME_TAB1);
                break;
            case 1:
                if (doIsLogin()) return;
                doChangeTitleLeftIcon(1);
                mTvHomeTabCircleFriends.setSelected(true);
                mTitleBarView.setTitleText("诚友圈");
                break;
            case R.id.tv_home_tab_resource:
                mPagerView.setCurrentItem(FragmentFactory.FRAGMENT_HOME_TAB2);
                break;
            case 2:
                doChangeTitleLeftIcon(1);
                mTvHomeTabResource.setSelected(true);
                mTitleBarView.setTitleText("资源");
                break;
            case R.id.tv_home_tab_shopping_friends:
                mPagerView.setCurrentItem(FragmentFactory.FRAGMENT_HOME_TAB3);
                break;
            case 3:
                doChangeTitleLeftIcon(1);
                mTvHomeTabShoppingFriends.setSelected(true);
                mTitleBarView.setTitleText("诚友购");
                break;
            case R.id.tv_home_tab_self:
                if (doIsLogin()) return;
                mPagerView.setCurrentItem(FragmentFactory.FRAGMENT_HOME_TAB4);
                break;
            case 4:
                if (doIsLogin()) return;
                doChangeTitleLeftIcon(0);
                mTvHomeTabSelf.setSelected(true);
                mTitleBarView.setTitleText("我的");
                break;
        }
    }

    private void doChangeTitleLeftIcon(int i) {
        switch (i) {
            case 0:
                mTitleBarView.setLeftBtnIcon(R.mipmap.personal_icon_set_1).setOnLeftBtnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActivityUtils.startActivity(HomeActivity.this, SettingActivity.class);
                    }
                });
                break;
            case 1:
                mTitleBarView.setLeftBtnIcon(R.mipmap.title_icon_search).setOnLeftBtnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActivityUtils.startActivity(HomeActivity.this, HomeSearchActivity.class);
                    }
                });
                break;
        }
    }

    private boolean doIsLogin() {
        if (!AppUtils.isLogin()) {
            ActivityUtils.startActivityAndFinish(HomeActivity.this, LoginActivity.class);
            return true;
        }
        return false;
    }


}